<?php
namespace Dao6;
use Dao6\Cache\FileCache;
use Dao6\Cache\ICache;

/**
 * Date: 16/8/12
 * Time: 下午4:10
 * 使用:
 *$ak = '57ac3816d9cb467d121dd48f'; //替换成你自己的AppKey
$sdk = \Dao6\SDK50R::getInstance($ak, false);
$res = $sdk->convert('http://www.jb51.net/article/34745.htm');
if(empty($res->error)){
echo '地址转换成功: ', $res->url;
}else{
echo $res->error;
}
 */
class SDK50R {

    private $ak = '';
    private $isHttps = false;

    private $userAgent = 'ShortURL Client (PHP) 1.0';

    /**
     * @var \Dao6\Cache\ICache
     */
    private $_cache;
    private $_enableCache = true;

    public function __construct($ak = '', $isHttps = false, $enableCache = true) {
        $this->ak = $ak;
        $this->isHttps = $isHttps;
        $this->_enableCache = $enableCache;

        if($this->_enableCache){
            $this->enableCache();
        }
    }

    public static function getInstance($ak = '', $isHttps = false){
        static $_instance;
        if(empty($_instance)){
            $_instance = new self($ak, $isHttps);
        }
        return $_instance;
    }

    public function setAppKey($ak = ''){
        $this->ak = $ak;
        return $this;
    }

    public function enableHttps(){
        $this->isHttps = true;
        return $this;
    }

    public function enableCache(ICache $cache = null){
        if($cache && $cache instanceof ICache){
            $this->_cache = $cache;
        }else if(!$this->_cache){
            $this->_cache = new FileCache();
        }
        $this->_enableCache = true;
        return $this;
    }

    public function disableCache(){
        $this->_enableCache = false;
        return $this;
    }

    /**
     * 将长地址转换为短地址
     * @param string $longUrl
     * @return SDK50R_Result
     */
    public function convert($longUrl = ''){
        $reqUrl = ($this->isHttps ? 'https' : 'http') . '://50r.cn/urls/add.json?' . ($this->ak ? 'ak=' . $this->ak . '&' : '') . 'url=' . urlencode($longUrl);
        if($this->_cache && $this->_enableCache){
            $result = $this->_cache->get($reqUrl);
        }
        if(empty($result)){
            $result = $this->_request($reqUrl);
            $this->_cache && $this->_enableCache && $this->_cache->set($reqUrl, $result, 600);
        }
        if($result[0] === '{'){
            $obj = json_decode($result);
            return new SDK50R_Result($obj->error, $obj->url, $result);
        }
        return new SDK50R_Result('Error: A network error or an error return data.');
    }

    private function _request($url = ''){
        if(extension_loaded('curl')){
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_USERAGENT, $this->userAgent);
            $output = curl_exec($ch);
            curl_close($ch);
        }else{
            $context = stream_context_create(array(
                'http'  => array(
                    'method'    => 'GET',
                    'header'    => 'User-Agent: ' . $this->userAgent
                )
            ));
            $output = file_get_contents($url, 0, $context);
        }
        return $output;
    }
}

class SDK50R_Result{
    public $error;
    public $url;
    public $raw;

    /**
     * Result constructor.
     * @param $error
     * @param $url
     */
    public function __construct($error = null, $url = null, $raw = null) {
        $this->error = $error;
        $this->url = $url;
        $this->raw = $raw;
    }

}
